package com.laxia.config;

import com.baidu.unbiz.easymapper.mapping.MappingHandler;
import com.baidu.unbiz.easymapper.mapping.ServiceLoaderHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.ServiceLoader;

/**
 * @author weishuai
 */
@Slf4j
@Component
public class SpringContextHolder implements ApplicationContextAware {

    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        // 防止easy-mapper异常
        ServiceLoader<MappingHandler> serviceLoader = ServiceLoaderHelper.getInstance().getServiceLoader();
        serviceLoader.forEach(o -> log.info("easy-mapper init: {}", o.getClass()));
        SpringContextHolder.applicationContext = applicationContext;
    }

    public static <T> T getBean(Class<T> clazz) {
        if (applicationContext != null) {
            try {
                return applicationContext.getBean(clazz);
            } catch (Throwable e) {
                e.printStackTrace();
            }
        }
        return null;
    }

}
